package com.test.qpbgboot.user.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.qpbgboot.base.enums.GeneralStatusEnum;
import com.test.qpbgboot.base.exception.ServiceException;
import com.test.qpbgboot.base.response.ResultStatus;
import com.test.qpbgboot.base.service.RedisService;
import com.test.qpbgboot.base.service.SMSService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.test.qpbgboot.base.utils.JwtTokenUtils;
import com.test.qpbgboot.show.mapper.EscortMapper;
import com.test.qpbgboot.show.mapper.TagMapper;
import com.test.qpbgboot.user.mapper.PersonalAccountMapper;
import com.test.qpbgboot.user.mapper.UserFollowingMapper;
import com.test.qpbgboot.user.mapper.UserMapper;
import com.test.qpbgboot.user.pojo.dto.*;
import com.test.qpbgboot.user.pojo.entity.PersonalAccount;
import com.test.qpbgboot.user.pojo.entity.TokenInfo;
import com.test.qpbgboot.user.pojo.entity.User;
import com.test.qpbgboot.user.pojo.entity.UserFollowing;
import com.test.qpbgboot.user.pojo.vo.UserFansVO;
import com.test.qpbgboot.user.pojo.vo.UserFollowingVO;
import com.test.qpbgboot.user.pojo.vo.UserVO;
import com.test.qpbgboot.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    @Value("${wechat.token}")
    private String token;
    @Value("${wechat.url}")
    private String url;
    @Value("${wechat.scope}")
    private String scope;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PersonalAccountMapper personalAccountMapper;
    @Autowired
    private UserFollowingMapper userFollowingMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private EscortMapper escortMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private static final String[] images =  {
            "https://oss-aliyun-zs.oss-cn-hangzhou.aliyuncs.com/timing-oss/1fdbb31e42d6cae7da84cf57cf2073a1.jpeg",
            "https://oss-aliyun-zs.oss-cn-hangzhou.aliyuncs.com/timing-oss/791837a889ebf4e76c2d6f185ad8a758.jpeg",
            "https://oss-aliyun-zs.oss-cn-hangzhou.aliyuncs.com/timing-oss/79720d49dacfc67b88ce9d56a68443a9.jpeg",
            "https://oss-aliyun-zs.oss-cn-hangzhou.aliyuncs.com/timing-oss/97fc60c68abadbb775c0fe8523951911.jpeg",
            "https://oss-aliyun-zs.oss-cn-hangzhou.aliyuncs.com/timing-oss/c15f42f4be7a30bc32f9b3cba9f4115c.jpg",
            "https://oss-aliyun-zs.oss-cn-hangzhou.aliyuncs.com/timing-oss/d68c2d6fb70b2e472d42d9df79413982.jpeg",
            "https://oss-aliyun-zs.oss-cn-hangzhou.aliyuncs.com/timing-oss/edfc47a731e9bf5be80e4cd76de7e8e6.jpeg",
    };


    @Override
    public boolean wxCheck(String signature, String timestamp, String nonce, String echostr) {
        // 初始化列表并添加token、timestamp和nonce
        List<String> list = new ArrayList<>();
        list.add(token);
        list.add(timestamp);
        list.add(nonce);
        // 对列表进行排序
        list.sort(String::compareTo);
        // 拼接列表中的字符串
        StringBuilder sb = new StringBuilder();
        for (String s : list) {
            sb.append(s);
        }
        String s = sb.toString();
        // 对拼接后的字符串进行SHA-1加密
        String sha1Hash = sha1(s);

        // 验证signature是否匹配
        if (sha1Hash.equals(signature)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * SHA-1加密算法
     * @param input 待加密的字符串
     * @return 加密后的字符串
     */
    private String sha1(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public Map<String, String> getQrCode() throws UnsupportedEncodingException {
        // 生成随机状态标识
        String state = UUID.randomUUID().toString();

        // 存储状态标识到Redis（示例使用伪代码）
        redisTemplate.opsForValue().set("wx:state:"+state, "pending", 300, TimeUnit.SECONDS);
        // 构造授权URL
        String redirectUrl = URLEncoder.encode(url+"/v1/user/redirect", "UTF-8");
        String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + appid + "&" +
                "redirect_uri=" + redirectUrl + "&" +
                "response_type=code&" +
                "scope=" + scope + "&" +
                "state=" + state + "#wechat_redirect";

        // 生成二维码图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        QrCodeUtil.generate(authUrl, 200, 200, "png", outputStream);
        String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());

        // 返回响应
        Map<String, String> response = new HashMap<>();
        response.put("state", state);
        response.put("qrCode", base64Image);
        return response;
    }

    @Override
    public void redirect(String code, String state, HttpServletResponse response) {
        System.out.println("code: " + code);
        System.out.println("state: " + state);

        // 获取access_token
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appid + "&" +
                "secret=" + secret + "&" +
                "code=" + code + "&" +
                "grant_type=authorization_code";

        // 发送HTTP请求（示例使用伪代码）
        ResponseEntity<String> tokenResponse = restTemplate.getForEntity(tokenUrl, String.class);
        String tokenResponseBody = tokenResponse.getBody();
        Map<String, Object> tokenResult = parseJsonToMap(tokenResponseBody);
        String openid = (String) tokenResult.get("openid");
        UserVO userVO = userMapper.selectUserVObyWxOpenId(openid);
        if(userVO ==null){
            TokenInfo tokenInfo = new TokenInfo();
            tokenInfo.setAccessToken((String) tokenResult.get("access_token"));
            tokenInfo.setExpiresIn((Integer) tokenResult.get("expires_in"));
            tokenInfo.setRefreshToken((String) tokenResult.get("refresh_token"));
            tokenInfo.setOpenid((String) tokenResult.get("openid"));
            tokenInfo.setScope((String) tokenResult.get("scope"));

            // 获取用户信息
            String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                    "access_token=" + tokenInfo.getAccessToken() + "&" +
                    "openid=" + tokenInfo.getOpenid()+ "&" +
                    "lang=zh_CN";
            ResponseEntity<String> userInfoResponse = restTemplate.getForEntity(userInfoUrl, String.class);
            String userInfoResponseBody = userInfoResponse.getBody();
            assert userInfoResponseBody != null;
            Map<String, Object> userInfoResult =parseJsonToMap(userInfoResponseBody);
            User userInfo = new User();
            userInfo.setWxOpenId((String) userInfoResult.get("openid"));
            userInfo.setUsername((String) userInfoResult.get("nickname"));
            userInfo.setImgUrl((String) userInfoResult.get("headimgurl"));
            userInfo.setCreateTime(new Date());
            userInfo.setUpdateTime(new Date());
            regUserIntoTables(userInfo);
            System.out.println("userInfo:"+userInfo);
        }

        // 生成JWT token
        String token = JwtTokenUtils.createJWT(openid,10);

        // 存储token到Redis
        redisTemplate.opsForValue().set("wx:token:"+state, token, 300, TimeUnit.SECONDS);
        // 更新Redis状态
        redisTemplate.opsForValue().set("wx:state:"+state, "authenticated", 300, TimeUnit.SECONDS);

    }

    @Override
    public Map<String, Object> checkLogin(String state) {
        Map<String, Object> response = new HashMap<>();

        // 从Redis获取登录状态
        String status =(String) redisTemplate.opsForValue().get("wx:state:"+state);

        if ("authenticated".equals(status)) {
            response.put("loggedIn", true);
            response.put("token", redisTemplate.opsForValue().get("wx:token:"+state));
            // 清除状态
            redisTemplate.delete("wx:state:"+state);
            redisTemplate.delete("wx:token:"+state);
        } else {
            response.put("loggedIn", false);
        }
        return response;
    }

    @Override
    public UserVO getUserInfoByWxOpenId(String token) {
        String openId = JwtTokenUtils.parseJWT(token, String.class);
        if(openId!=null){
            return userMapper.selectUserVObyWxOpenId(openId);
        }
        return null;
    }

    /**
     * 解析JSON字符串为Map
     * @param json JSON字符串
     * @return 解析后的Map对象
     */
    private Map<String, Object> parseJsonToMap(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        // 配置JSON解析器
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        try {
            return objectMapper.readValue(json.getBytes(StandardCharsets.UTF_8),
                    new TypeReference<Map<String, Object>>() {});
        } catch (IOException e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }


    @Override
    public void reg(UserRegParam userRegParam) {
        log.debug("用户注册业务，参数:{}", userRegParam);
        UserVO userVO = userMapper.selectUserVObyUsername(userRegParam.getUsername());
        if (userVO != null) {
            throw new ServiceException(ResultStatus.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        regUserIntoTables(user);
    }

    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录业务，参数:{}", userLoginParam);

        String username = userLoginParam.getUsername();
        String password = userMapper.selectPasswordByUsername(
                username);
        if (password == null) {
            throw new ServiceException(ResultStatus.USERNAME_ERROR);
        } else if (password.equals(userLoginParam.getPassword())) {
            UserVO userVO = userMapper.selectUserVObyUsername(username);
            additionalField(userVO);
            return userVO;
        } else {
            throw new ServiceException(ResultStatus.PASSWORD_ERROR);
        }
    }

//    @Override
//    public UserVO wechatLogin(String code) {
//        log.debug("用户微信登录业务，参数:{}", code);
//
//        String openId = getOpenId(code);
//        UserVO userVO;
//
//        if (openId != null) {
//            userVO = userMapper.selectUserVObyWxOpenId(openId);
//            if (userVO == null) {
//                User user = new User();
//                user.setUsername("user_" + openId.substring(0, 10));
//                user.setWxOpenId(openId);
//                regUserIntoTables(user);
//            } else {
//                additionalField(userVO);
//            }
//        } else {
//            throw new ServiceException(ResultStatus.ILLEGAL_ARGUMENT, "微信信息错误");
//        }
//
//        log.debug("用户微信登录业务 入参:{},出参:{}", code, userVO);
//        return userVO;
//    }

    @Override
    public UserVO phoneLogin(PhoneLoginParam phoneLoginParam) {
        log.debug("用户手机号登录业务 入参:{}", phoneLoginParam);

        String phone = phoneLoginParam.getPhone();
        String captcha = phoneLoginParam.getCaptcha();
        boolean check = redisService.checkValue(
                SMSService.getPhoneCaptchaRedisKey(phone),
                captcha);
        if (!check) {
            throw new ServiceException(ResultStatus.INCORRECT_CAPTCHA);
        }

        UserVO userVO = userMapper.selectUserVObyPhone(phone);
        if (userVO == null) {
//            throw new ServiceException(
//                    ResultStatus.FAILURE.getCode(),
//                    "该手机号未注册");
            User user = new User();
            user.setPhone(phone);
            user.setUsername(UUID.randomUUID().toString().substring(0,8));
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            regUserIntoTables(user);
            userVO = userMapper.selectUserVObyPhone(phone);
        }
        additionalField(userVO);
        log.debug("用户手机号登录业务 入参:{},出参:{}", phoneLoginParam, userVO);
        return userVO;
    }

    @Override
    public void passwordChange(UserPasswordParam userPasswordParam) {
        log.debug("用户密码修改业务，参数:{}", userPasswordParam);
        UserVO userVO = userMapper.selectUserVObyId(userPasswordParam.getId());
        if (userVO == null) {
            throw new ServiceException(ResultStatus.INVALID_ID);
        }
        String oldPassword = userMapper.selectPasswordByUsername(userVO.getUsername());
        if (userPasswordParam.getOldPassword().equals(oldPassword)) {
            User user = new User();
            BeanUtils.copyProperties(userVO, user);
            BeanUtils.copyProperties(userPasswordParam, user);
            userMapper.update(user);
        } else {
            throw new ServiceException(ResultStatus.PASSWORD_ERROR);
        }
    }

    @Override
    public void userLogOff(Long userId) {
        log.debug("用户注销业务，参数:{}", userId);

        User user = new User();
        user.setId(userId);
        user.setStatus(GeneralStatusEnum.DISABLE.getValue());
        userMapper.changeStatus(user);

        PersonalAccount account = new PersonalAccount();
        account.setUserId(userId);
        account.setStatus(GeneralStatusEnum.DISABLE.getValue());
        personalAccountMapper.updateByUserId(account);

        escortMapper.updateVisibleByUserId(userId, GeneralStatusEnum.DISABLE.getValue());
    }

    @Override
    public void userSave(UserSaveParam userSaveParam) {
        log.debug("用户基本信息保存业务，参数:{}", userSaveParam);
        UserVO userVO = userMapper.selectUserVObyUsername(userSaveParam.getUsername());
        if (userVO != null && !userVO.getId().equals(userSaveParam.getId())) {
            throw new ServiceException(ResultStatus.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userSaveParam, user);

        Date date = userSaveParam.getBirthday();
        if (date != null) {
            LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            Period period = Period.between(localDate, LocalDate.now());
            Integer age = period.getYears();
            user.setAge(age);
        } else {
            user.setAge(null);
        }
        List<Long> tagIdList = userSaveParam.getTagIdList();
        if (tagIdList != null && !tagIdList.isEmpty()) {
            if (tagIdList.size() != tagMapper.selectCountByIdList(tagIdList)) {
                throw new ServiceException(ResultStatus.INVALID_ID, "标签id无效");
            }
            String tagIds = tagIdList.stream().filter(Objects::nonNull)
                    .map(String::valueOf).collect(Collectors.joining(","));
            user.setTagIds(tagIds);
        }
        userMapper.update(user);
    }

    @Override
    public UserVO userSelect(Long userId) {
        log.debug("用户基本信息查询业务:{}", userId);
        UserVO userVO = userMapper.selectUserVObyId(userId);
        if (userVO == null) {
            throw new ServiceException(ResultStatus.INVALID_ID);
        }
        additionalField(userVO);
        log.debug("用户查询结果:{}", userVO);
        return userVO;
    }

    @Override
    public void userFollow(UserFollowParam userFollowParam) {
        log.debug("用户关注业务，参数:{}", userFollowParam);
        UserVO userVO = userMapper.selectUserVObyId(userFollowParam.getId());
        UserVO userFollowingVO = userMapper.selectUserVObyId(userFollowParam.getFollowingId());
        if (userVO == null || userFollowingVO == null
                || GeneralStatusEnum.DISABLE.getValue().equals(userVO.getStatus())
                || GeneralStatusEnum.DISABLE.getValue().equals(userFollowingVO.getStatus())) {
            throw new ServiceException(ResultStatus.INVALID_ID);
        }
        UserFollowing userFollowing = new UserFollowing();
        userFollowing.setUserId(userFollowParam.getId());
        userFollowing.setFollowingId(userFollowParam.getFollowingId());
        Long userFollowingId = userFollowingMapper
                .selectUserFollowingIdByUserFollowing(userFollowing);
        if (userFollowingId != null) {
            throw new ServiceException(ResultStatus.REPEAT_OPERATION);
        }
        userFollowingMapper.insert(userFollowing);
        User user;
        Long fansNum = userVO.getFansNum();
        Long followingNum = userVO.getFollowingNum();
        if (fansNum % 50 == 0 || followingNum % 50 == 0) {
            checkFansAndFollowNum(userVO);
        } else {
            user = new User();
            BeanUtils.copyProperties(userVO, user);
            user.setFollowingNum(userVO.getFollowingNum() + 1);
            userMapper.update(user);
        }
        fansNum = userFollowingVO.getFansNum();
        followingNum = userFollowingVO.getFollowingNum();
        if (fansNum % 50 == 0 || followingNum % 50 == 0) {
            checkFansAndFollowNum(userFollowingVO);
        } else {
            user = new User();
            BeanUtils.copyProperties(userFollowingVO, user);
            user.setFansNum(userFollowingVO.getFansNum() + 1);
            userMapper.update(user);
        }
    }

    @Override
    public void userUnfollow(UserFollowParam userFollowParam) {
        log.debug("用户取消关注业务，参数:{}", userFollowParam);
        UserVO userVO = userMapper.selectUserVObyId(userFollowParam.getId());
        UserVO userFollowingVO = userMapper.selectUserVObyId(userFollowParam.getFollowingId());
        if (userVO == null || userFollowingVO == null
                || GeneralStatusEnum.DISABLE.getValue().equals(userVO.getStatus())) {
            throw new ServiceException(ResultStatus.INVALID_ID);
        }
        UserFollowing userFollowing = new UserFollowing();
        userFollowing.setUserId(userFollowParam.getId());
        userFollowing.setFollowingId(userFollowParam.getFollowingId());
        Long userFollowingId = userFollowingMapper
                .selectUserFollowingIdByUserFollowing(userFollowing);
        if (userFollowingId == null) {
            throw new ServiceException(ResultStatus.FAILURE);
        } else {
            userFollowingMapper.deleteById(userFollowingId);
        }
        User user;
        Long fansNum = userVO.getFansNum();
        Long followingNum = userVO.getFollowingNum();
        if (fansNum % 50 == 0 || followingNum % 50 == 0) {
            checkFansAndFollowNum(userVO);
        } else {
            user = new User();
            BeanUtils.copyProperties(userVO, user);
            user.setFollowingNum(userVO.getFollowingNum() - 1);
            userMapper.update(user);
        }
        fansNum = userFollowingVO.getFansNum();
        followingNum = userFollowingVO.getFollowingNum();
        if (fansNum % 50 == 0 || followingNum % 50 == 0) {
            checkFansAndFollowNum(userFollowingVO);
        } else {
            user = new User();
            BeanUtils.copyProperties(userFollowingVO, user);
            user.setFansNum(userFollowingVO.getFansNum() - 1);
            userMapper.update(user);
        }
    }

    @Override
    public List<UserFollowingVO> followingSelect(Long userId) {
        log.debug("关注对象查询业务，参数:{}", userId);
        UserVO userVO = userMapper.selectUserVObyId(userId);
        if (userVO == null) {
            throw new ServiceException(ResultStatus.INVALID_ID);
        }
        List<UserFollowingVO> followingList = userFollowingMapper.selectUserFollowingVObyUserId(userId);
        if (followingList == null) {
            followingList = new ArrayList<>();
        }
        if (!followingList.isEmpty()) {
            followingList.forEach(userFollowingVO -> {
                userFollowingVO.setFollowingUser(userMapper.selectUserVObyId(userFollowingVO.getFollowingId()));
            });
        }
        if (userVO.getFollowingNum() != followingList.size()) {
            User user = new User();
            BeanUtils.copyProperties(userVO, user);
            user.setFollowingNum((long) followingList.size());
            userMapper.update(user);
        }
        log.debug("关注对象查询结果:{}", followingList);
        return followingList;
    }

    @Override
    public List<UserFansVO> fansSelect(Long userId) {
        log.debug("粉丝用户查询业务，参数:{}", userId);
        UserVO userVO = userMapper.selectUserVObyId(userId);
        if (userVO == null) {
            throw new ServiceException(ResultStatus.INVALID_ID);
        }
        List<UserFansVO> fansList = userFollowingMapper.selectUserFansVObyUserId(userId);
        if (fansList == null) {
            fansList = new ArrayList<>();
        }
        if (!fansList.isEmpty()) {
            fansList.forEach(userFansVO -> {
                userFansVO.setFanUser(userMapper.selectUserVObyId(userFansVO.getUserId()));
            });
        }
        if (userVO.getFansNum() != fansList.size()) {
            User user = new User();
            BeanUtils.copyProperties(userVO, user);
            user.setFansNum((long) fansList.size());
            userMapper.update(user);
        }
        log.debug("粉丝用户查询结果:{}", fansList);
        return fansList;
    }

    /**
     * 注册用户信息，放入对应的表
     */
    private void regUserIntoTables(User user) {
        log.debug("注册用户信息进入用户表和账户表:{}", user);
        if(user.getImgUrl()==null || user.getImgUrl().isEmpty()){
            int index = new Random().nextInt(7);
            user.setImgUrl(images[index]);
        }
        user.setStatus(GeneralStatusEnum.ENABLE.getValue());
        userMapper.insert(user);
        PersonalAccount account = new PersonalAccount();
        account.setUserId(user.getId());
        account.setAccountBalance(BigDecimal.ZERO);
        account.setPoints(0L);
        account.setStatus(GeneralStatusEnum.ENABLE.getValue());
        personalAccountMapper.insert(account);
    }

//    /**
//     * 业务服务器通过code + 仅保存在服务器的appsecret参数，
//     * 向：微信开放平台接口发起网络请求详情。
//     */
//    private String getOpenId(String code) {
//        log.debug("向微信平台请求详情 入参:code={}", code);
//
//        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
//                "appid=" + appId +
//                "&secret=" + appSecret +
//                "&js_code=" + code +
//                "&grant_type=authorization_code";
//        String jsonData = restTemplate.getForObject(url, String.class);
//        WechatLoginData wechatLoginData =
//                JsonUtils.fromJson(jsonData, WechatLoginData.class);
//        log.debug("微信返回的数据 wechatLoginData={}", wechatLoginData);
//        if (wechatLoginData == null) {
//            return null;
//        }
//        return wechatLoginData.getOpenId();
//    }

    /**
     * 补充额外属性
     */
    public void additionalField(UserVO userVO) {
        log.debug("userVO补充额外属性:{}", userVO);

        String tags = userVO.getTagIds();
        if (tags != null && !tags.trim().isEmpty()) {
            List<Long> tagIds = Arrays.stream(tags.split(","))
                    .map(Long::parseLong).collect(Collectors.toList());
            userVO.setTagIdList(tagIds);
        }
        userVO.setEscortIs(escortMapper.selectCountByUserId(userVO.getId()) == 1);
    }

    /**
     * 检查粉丝数和关注数
     */
    private void checkFansAndFollowNum(UserVO userVO) {
        log.debug("检查粉丝数和关注数:{}", userVO);
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        Long userId = userVO.getId();
        user.setFollowingNum(userFollowingMapper.selectFollowingNumByUserId(userId));
        user.setFansNum(userFollowingMapper.selectFansNumByUserId(userId));
        userMapper.update(user);
    }


}
